package com.swotxu.screwweb.util;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Date: 2021/7/15 11:08
 * @Author: xu.hai
 */
@Component
public class ReentrantReadWriteLockUtil {
    // 读写锁集合
    private volatile Map<String, ReentrantReadWriteLock> locks = new ConcurrentHashMap<>();

    public ReentrantReadWriteLock getReadWriteLock(String key) {
        return locks.compute(key, (k, v) -> Objects.isNull(v) ? new ReentrantReadWriteLock() : v);
    }

    public ReentrantReadWriteLock.ReadLock getReadLock(String key) {
        return getReadWriteLock(key).readLock();
    }

    public ReentrantReadWriteLock.WriteLock getWriteLock(String key) {
        return getReadWriteLock(key).writeLock();
    }

}
